import tkinter as tk
from tkinter import ttk, messagebox
from student_score_manager import StudentScoreManager


class StudentScoreGUI:
    def __init__(self, root):
        self.root = root
        self.root.title("学生成绩管理系统")
        self.root.geometry("600x500")
        
        self.manager = StudentScoreManager()
        
        # 连接数据库
        if not self.manager.connect():
            messagebox.showerror("错误", "数据库连接失败！")
            return
        
        self.create_widgets()
        
    def create_widgets(self):
        # 创建主框架
        main_frame = ttk.Frame(self.root, padding="10")
        main_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        
        # 输入框架
        input_frame = ttk.LabelFrame(main_frame, text="学生成绩信息", padding="10")
        input_frame.grid(row=0, column=0, columnspan=2, sticky=(tk.W, tk.E), pady=(0, 10))
        
        # 学号输入
        ttk.Label(input_frame, text="学号:").grid(row=0, column=0, sticky=tk.W, padx=(0, 5))
        self.student_id_var = tk.StringVar()
        self.student_id_entry = ttk.Entry(input_frame, textvariable=self.student_id_var, width=20)
        self.student_id_entry.grid(row=0, column=1, padx=(0, 20))
        
        # 课程编号输入
        ttk.Label(input_frame, text="课程编号:").grid(row=0, column=2, sticky=tk.W, padx=(0, 5))
        self.course_id_var = tk.StringVar()
        self.course_id_entry = ttk.Entry(input_frame, textvariable=self.course_id_var, width=20)
        self.course_id_entry.grid(row=0, column=3)
        
        # 成绩输入
        ttk.Label(input_frame, text="成绩:").grid(row=1, column=0, sticky=tk.W, padx=(0, 5), pady=(10, 0))
        self.score_var = tk.StringVar()
        self.score_entry = ttk.Entry(input_frame, textvariable=self.score_var, width=20)
        self.score_entry.grid(row=1, column=1, pady=(10, 0))
        
        # 按钮框架
        button_frame = ttk.Frame(main_frame)
        button_frame.grid(row=1, column=0, columnspan=2, pady=(0, 10))
        
        # 操作按钮
        ttk.Button(button_frame, text="添加", command=self.add_score).grid(row=0, column=0, padx=(0, 5))
        ttk.Button(button_frame, text="修改", command=self.update_score).grid(row=0, column=1, padx=(0, 5))
        ttk.Button(button_frame, text="删除", command=self.delete_score).grid(row=0, column=2, padx=(0, 5))
        ttk.Button(button_frame, text="查询", command=self.query_scores).grid(row=0, column=3)
        
        # 结果显示框架
        result_frame = ttk.LabelFrame(main_frame, text="查询结果", padding="10")
        result_frame.grid(row=2, column=0, columnspan=2, sticky=(tk.W, tk.E, tk.N, tk.S))
        
        # 创建树形控件显示结果
        columns = ('学号', '课程编号', '成绩', '创建时间', '更新时间')
        self.tree = ttk.Treeview(result_frame, columns=columns, show='headings', height=15)
        
        # 设置列标题
        for col in columns:
            self.tree.heading(col, text=col)
            self.tree.column(col, width=100)
        
        # 滚动条
        scrollbar = ttk.Scrollbar(result_frame, orient=tk.VERTICAL, command=self.tree.yview)
        self.tree.configure(yscrollcommand=scrollbar.set)
        
        self.tree.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        scrollbar.grid(row=0, column=1, sticky=(tk.N, tk.S))
        
        # 配置网格权重
        main_frame.columnconfigure(0, weight=1)
        main_frame.rowconfigure(2, weight=1)
        result_frame.columnconfigure(0, weight=1)
        result_frame.rowconfigure(0, weight=1)
        self.root.columnconfigure(0, weight=1)
        self.root.rowconfigure(0, weight=1)
        
        # 初始加载所有数据
        self.load_all_scores()
    
    def add_score(self):
        """添加成绩"""
        student_id = self.student_id_var.get().strip()
        course_id = self.course_id_var.get().strip()
        score = self.score_var.get().strip()
        
        if not all([student_id, course_id, score]):
            messagebox.showwarning("警告", "请填写所有字段！")
            return
        
        try:
            score_float = float(score)
            if score_float < 0 or score_float > 100:
                messagebox.showwarning("警告", "成绩应在0-100之间！")
                return
        except ValueError:
            messagebox.showerror("错误", "成绩必须是数字！")
            return
        
        if self.manager.add_score(student_id, course_id, score_float):
            messagebox.showinfo("成功", "成绩添加成功！")
            self.clear_inputs()
            self.load_all_scores()
        else:
            messagebox.showerror("错误", "成绩添加失败！可能是重复记录。")
    
    def update_score(self):
        """修改成绩"""
        student_id = self.student_id_var.get().strip()
        course_id = self.course_id_var.get().strip()
        score = self.score_var.get().strip()
        
        if not all([student_id, course_id, score]):
            messagebox.showwarning("警告", "请填写所有字段！")
            return
        
        try:
            score_float = float(score)
            if score_float < 0 or score_float > 100:
                messagebox.showwarning("警告", "成绩应在0-100之间！")
                return
        except ValueError:
            messagebox.showerror("错误", "成绩必须是数字！")
            return
        
        if self.manager.update_score(student_id, course_id, score_float):
            messagebox.showinfo("成功", "成绩修改成功！")
            self.clear_inputs()
            self.load_all_scores()
        else:
            messagebox.showerror("错误", "成绩修改失败！请检查记录是否存在。")
    
    def delete_score(self):
        """删除成绩"""
        student_id = self.student_id_var.get().strip()
        course_id = self.course_id_var.get().strip()
        
        if not all([student_id, course_id]):
            messagebox.showwarning("警告", "请填写学号和课程编号！")
            return
        
        if messagebox.askyesno("确认", "确定要删除这条记录吗？"):
            if self.manager.delete_score(student_id, course_id):
                messagebox.showinfo("成功", "成绩删除成功！")
                self.clear_inputs()
                self.load_all_scores()
            else:
                messagebox.showerror("错误", "成绩删除失败！请检查记录是否存在。")
    
    def query_scores(self):
        """查询成绩"""
        student_id = self.student_id_var.get().strip()
        course_id = self.course_id_var.get().strip()
        
        if student_id and course_id:
            # 精确查询
            result = self.manager.query_score(student_id, course_id)
            self.display_results([result] if result else [])
        elif student_id:
            # 按学号查询
            results = self.manager.query_scores_by_student(student_id)
            self.display_results(results)
        elif course_id:
            # 按课程查询
            results = self.manager.query_scores_by_course(course_id)
            self.display_results(results)
        else:
            # 查询所有
            self.load_all_scores()
    
    def load_all_scores(self):
        """加载所有成绩"""
        results = self.manager.query_all_scores()
        self.display_results(results)
    
    def display_results(self, results):
        """显示查询结果"""
        # 清空现有数据
        for item in self.tree.get_children():
            self.tree.delete(item)
        
        # 插入新数据
        if results:
            for row in results:
                self.tree.insert('', tk.END, values=(
                    row['student_id'],
                    row['course_id'],
                    row['score'],
                    row['created_at'].strftime('%Y-%m-%d %H:%M:%S'),
                    row['updated_at'].strftime('%Y-%m-%d %H:%M:%S')
                ))
    
    def clear_inputs(self):
        """清空输入框"""
        self.student_id_var.set('')
        self.course_id_var.set('')
        self.score_var.set('')
    
    def __del__(self):
        """析构函数，关闭数据库连接"""
        if hasattr(self, 'manager'):
            self.manager.disconnect()


def main():
    root = tk.Tk()
    app = StudentScoreGUI(root)
    root.mainloop()


if __name__ == "__main__":
    main()